package cn.iluwen.airline.Services;

import cn.iluwen.airline.DTOs.user.request.CheckInRequest;
import cn.iluwen.airline.DTOs.user.response.OrderResponse;
import cn.iluwen.airline.Entities.OrderDetail;
import cn.iluwen.airline.Entities.Seat;
import cn.iluwen.airline.Mapper.OrderDetailMapper;
import cn.iluwen.airline.Mapper.SeatMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 值机服务类
 * 处理用户值机选座功能
 */
@Service
public class CheckInService {
    
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    
    @Autowired
    private SeatMapper seatMapper;
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 获取航班可用座位
     * @param flightId 航班ID
     * @param ticketClass 舱位等级
     * @return 可用座位列表
     */
    public List<Seat> getAvailableSeats(String flightId, String ticketClass) {
        if (ticketClass != null && !ticketClass.isEmpty()) {
            // 根据舱位等级查询可用座位
            List<Seat> allSeats = seatMapper.findByFlightIdAndClass(flightId, ticketClass);
            // 过滤出未被占用的座位
            return allSeats.stream()
                    .filter(seat -> !seat.getIsOccupied())
                    .toList();
        } else {
            // 查询所有可用座位
            return seatMapper.findAvailableSeatsByFlightId(flightId);
        }
    }
    
    /**
     * 用户值机选座
     * @param userId 用户ID
     * @param request 值机请求
     * @return 更新后的订单
     */
    @Transactional
    public OrderResponse checkIn(String userId, CheckInRequest request) {
        // 查询订单详情
        OrderDetail orderDetail = orderDetailMapper.findById(request.getDetailId());
        if (orderDetail == null) {
            throw new RuntimeException("订单详情不存在");
        }
        
        // 查询对应的座位
        Seat seat = seatMapper.findByFlightIdAndSeatNumber(orderDetail.getFlightId(), request.getSeatNumber());
        if (seat == null) {
            throw new RuntimeException("座位不存在");
        }
        
        // 检查座位是否可用
        if (seat.getIsOccupied()) {
            throw new RuntimeException("座位已被占用");
        }
        
        // 检查座位舱位等级是否与票面一致
        if (!seat.getSeatClass().equals(orderDetail.getTicketClass())) {
            throw new RuntimeException("座位舱位等级与票面不符");
        }
        
        // 如果已经选过座，需要释放之前的座位
        if (orderDetail.getSeatId() != null) {
            seatMapper.updateOccupiedStatus(orderDetail.getSeatId(), false);
        }
        
        // 更新座位状态为已占用
        seatMapper.updateOccupiedStatus(seat.getSeatId(), true);
        
        // 更新订单详情的座位和值机状态
        orderDetailMapper.updateCheckIn(orderDetail.getDetailId(), seat.getSeatId(), true);
        
        // 返回更新后的订单详情
        return orderService.getOrderDetail(userId, orderDetail.getOrderId());
    }
} 